/*
 * 地址选择
 */
'use strict';
import React, { Component } from 'react';
import {
    View,
    Text,
    StyleSheet,
    Image,
    ListView,
    RefreshControl,
    ActivityIndicator,
    TouchableOpacity,
    Dimensions,
    Animated,
    TouchableHighlight,
    AsyncStorage,
    PixelRatio,
    TextInput,
    Alert,
    ScrollView
} from 'react-native';

import GridView from 'react-native-gridview';


import Toast from 'antd-mobile/lib/toast';
import List from 'antd-mobile/lib/list';
import Flex from 'antd-mobile/lib/flex';
import Carousel from 'antd-mobile/lib/carousel';
import Popup from 'antd-mobile/lib/popup';
import Grid from 'antd-mobile/lib/grid';
import NavTitle from '../component/NavTitle';
import * as QQAPI from 'react-native-qq';
import * as WechatAPI from 'react-native-wx';
import Communications from '../utils/Communications';

const Item = List.Item;

import XFetch from '../XFetch';
import ErWeiMaService from './ErweimaService';
import MyWebView from '../utils/MyWebView';


var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

let _loginStauts = false;

class ServiceShop extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: ds.cloneWithRows([]),
            summary:void 0,
            title:void 0,
            date:void 0,
            address:void 0,
            content:void 0,
            imgs:[],
            comment:void 0,
            focuimgs:[],
            username:'默认用户',
            hits:0,
            telphone:'10086',
            heights:[],
            lat:void 0,
            lng:void 0,
            isRenZheng:false,
            baoZeng_Money:0,
            text:'http://www.weiweigou.com'
        }

    }

    _getLoginStatus(){
        AsyncStorage.getItem('serveid').then(value=>{
            if(!value){
                _loginStauts = true;
            }
        });
    }


    componentDidMount(){
        this._getLoginStatus();
        AsyncStorage.getItem('username').then(data=>{
            if(data){
                this.setState({
                    username:data
                })
            }
        });
        XFetch(`http://www.weiweigo.com/app/server.aspx?method=showDetail&serveid=${this.props.id}`,{
            method:'GET',
        }).then(data=>{
            this.setState({
                hits:data.hits,
                lat:data.lat,
                lng:data.lon,
                telphone:data.tel,
                text:`http://www.weiweigo.com/servedetail.aspx?serveid=${data.serveId}&aid=${data.addressId}`,
                summary:data.summary,
                title:data.title,
                date:data.datetime.split(' '),
                address:data.addressDetail,
                content:data.content,
                isRenZheng:data.isRenZheng,
                baoZeng_Money:data.baoZeng_Money,
                imgs:data.content_img?JSON.parse(data.content_img):[],
                focuimgs:data.focusimg?JSON.parse(data.focusimg):[]
            },this._getcomment.bind(this));
        });
    }

    _getcomment(){
        let _heights = [];
        this.state.imgs.map(ele=>{
            Image.getSize(`http://www.weiweigo.com${ele.src}`, (width, height) => {
                _heights.push(height/PixelRatio.get());
            });
        });
        XFetch(`http://www.weiweigo.com/app/content.aspx?method=commentList&channelid=1&id=${this.props.id}&p=1`,{
            method:'GET',
        }).then(data=>{
            this.setState({
                dataSource:ds.cloneWithRows(data),
                heights:_heights
            })
        });
    }

    _renderRow(rowData, sectionID, rowID){
        return(
            <View style={styles.commentView}>
                <Image
                    source={{uri:rowData.IMGURL?`http://www.weiweigo.com${rowData.IMGURL}`:'http://www.weiweigo.com/images/m_head.png'}}
                    style={styles.logoImg}/>
                <View style={{flex:1}}>
                    <Text style={styles.commentName}>{rowData.NAME?rowData.NAME:'默认用户'}</Text>
                    <Text style={styles.conmentContent}>{rowData.COMMENTCON}</Text>
                </View>
                <Text style={styles.commentDate}>{rowData.ADDDATE.split(' ')[0]}</Text>
            </View>
        )
    }

    _submit(){
        if(_loginStauts){
            Toast.info('请先登录',2);
            return;
        }
        fetch(`http://www.weiweigo.com/app/content.aspx?method=comment`,{
            method:'POST',
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            body:`channelid=1&id=${this.props.id}&plcon=${this.state.comment}`
        }).then(data=>{
            data.json().then(data=>{
                if(data.success){
                    Toast.success('评论成功', 1);
                    this._getcomment();
                }
            });
        });
    }

    _renderImage(){
        return this.state.imgs.map((ele,index)=>{
           return (
               <Image resizeMode="stretch" key={`ttt${index}`} source={{uri:`http://www.weiweigo.com${ele.src}`}} style={[styles.infoImg,{
                    marginTop:10,height:this.state.heights[index]
                }]}></Image>
           )
        });
    }

    _getErweima(){
        this.props.navigator.push({
            name:'ErWeiMaService',
            component:ErWeiMaService,
            params:{
                id:this.props.id
            }
        })
    }

    _navigation(){
        let _pos = '25.049214,102.703629';
        if(this.state.lat){
            _pos = this.state.lat + ','+this.state.lng;
        }
        this.props.navigator.push({
            name:'MyWebView',
            component:MyWebView,
            params:{
                path:`http://apis.map.qq.com/tools/poimarker?type=0&marker=coord:${_pos};title:${this.state.title}&key=55JBZ-6L6KU-5Z6V3-25OQM-CXWJ5-RJFT2&referer=myapp`
            }
        })
    }

    render() {
        return (
            <View style={styles.container}>
                <NavTitle
                    title='服务详情'
                    headColor = '#fbdc3a'
                    leftButton = {true}
                    leftImg={require('../imgs/left.png')}
                    leftText = {'返回'}
                    leftHander = {()=>{
                        this.props.navigator.pop();
                    }}
                    rightButton={true}
                    rightText = {'分享'}
                    rightHander={()=>{
                        Popup.show(
                            <Grid hasLine={false} onClick={(ele,index)=>{
                                if(index === 0){
                                    WechatAPI.shareToSession({
                                        type: 'text',
                                        text: this.state.text
                                    })
                                }else if(index === 1){
                                    WechatAPI.shareToTimeline({
                                        type: 'text',
                                        text: this.state.text
                                    })
                                }else if(index === 2){
                                    QQAPI.shareToQQ({
                                        type: 'news',
                                        title: '微微购',
                                        description: '微微购服务详情分享',
                                        webpageUrl: this.state.text,
                                        imageUrl: 'http://ouxiurkf8.bkt.clouddn.com/2017-08-21_DOtOgI4n.png',
                                    });
                                }else if(index === 3){
                                    QQAPI.shareToQzone({
                                        type: 'news',
                                        title: '微微购',
                                        description: '微微购服务详情分享',
                                        webpageUrl: this.state.text,
                                        imageUrl: 'http://ouxiurkf8.bkt.clouddn.com/2017-08-21_DOtOgI4n.png',
                                    });
                                }
                                Popup.hide();
                            }} data={[{
                                icon: require('../imgs/erweima2.png'),
                                text: `分享好友`,
                            },{
                                icon: require('../imgs/erweima3.png'),
                                text: `分享朋友圈`,
                            },{
                                icon: require('../imgs/erweima5.png'),
                                text: `分享QQ`,
                            },{
                                icon: require('../imgs/erweima6.png'),
                                text: `分享空间`,
                            }]} columnNum={3} renderItem={(ele,index)=>{
                                return (
                                    <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
                                        <Image source={ele.icon} style={{width:42,height:42}}/>
                                        <Text style={{marginTop:5}}>{ele.text}</Text>
                                    </View>
                                )
                            }}/>
                        ,{animationType: 'slide-up',onMaskClose(){},maskClosable:true});
                    }}
                />
                <ScrollView
                    showsVerticalScrollIndicator={false}
                >
                    <View style={{height:100}}>
                        <Carousel
                            autoplay={true}
                            infinite
                            dots = {false}
                        >
                            {this.state.focuimgs.map((ii,index) => (
                                <Image
                                    key={`sliderImg${index}`}
                                    source={{uri:`http://www.weiweigo.com${ii.src}`}}
                                    style={styles.sliderImage}
                                    resizeMode="stretch"
                                />
                            ))}
                        </Carousel>
                    </View>
                    <View style={styles.content}>
                        <View style={{padding:10}}>
                        <View style={styles.head}>
                            <Text style={styles.title}>{this.state.title}</Text>
                            <Text style={styles.scanCount}>浏览次数:{this.state.hits}</Text>
                        </View>
                        <View style={styles.service}>
                            <Text
                                numberOfLines={1}
                                style={styles.serviceDetail}
                            >
                                发布时间:{this.state.date}
                            </Text>
                            <Text
                                numberOfLines={1}
                                style={[styles.serviceDetail,{marginTop:5}]}
                            >
                                {this.state.address}
                            </Text>
                        </View>
                        <View style={styles.tabIcon}>
                            <View style={[styles.tabClick,{marginLeft:0}]}>
                                <Image style={[styles.tabImg,{width:22}]} source={this.state.isRenZheng?require('../imgs/select.png'):require('../imgs/selectNo.png')}></Image>
                                <Text style={styles.tabText}>资历认证</Text>
                            </View>
                            <View style={styles.tabClick}>
                                <Image style={styles.tabImg} source={this.state.baoZeng_Money != 0?require('../imgs/select.png'):require('../imgs/selectNo.png')}></Image>
                                <Text style={styles.tabText}>保证金</Text>
                            </View>
                            <TouchableOpacity style={styles.tabClick} onPress={this._getErweima.bind(this)}>
                                <Image style={styles.tabImg} source={require('../imgs/select.png')}></Image>
                                <Text style={styles.tabText}>生成二维码</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.tabClick} onPress={this._navigation.bind(this)}>
                                <Image style={styles.tabImg} source={require('../imgs/select.png')}></Image>
                                <Text style={styles.tabText}>一键导航</Text>
                            </TouchableOpacity>
                        </View>


                        </View>

                        <View style={styles.remark}>
                            <View style={styles.remarkLabel}>
                                <Text style={[styles.remarkText,styles.remarkLebelText]}>
                                    简介:
                                </Text>
                            </View>
                            <View style={styles.remarkContent}>
                                <Text style={[styles.remarkText,styles.remarkContentText]}>
                                    {this.state.summary}
                                </Text>
                            </View>
                        </View>

                        <View style={styles.imgsText}>
                            {
                                this._renderImage()
                            }
                            <Text style={styles.infoText}>{this.state.content}</Text>
                        </View>

                        <ListView
                            dataSource={this.state.dataSource}
                            renderRow={this._renderRow.bind(this)}
                            enableEmptySections={true}
                        />

                        <View style={styles.evaInfo}>
                            <Text style={styles.nickLabel}>昵称</Text>
                            <Text style={styles.nickName}>{this.state.username}</Text>
                        </View>
                        <View style={styles.evaView}>
                            <TextInput
                                style={styles.evaInput}
                                placeholder = '请输入评价内容'
                                onChangeText={(value)=>{
                                    this.setState({
                                        comment:value
                                    })
                                }}
                            />
                        </View>
                        <View style={{padding:15}}>
                            <TouchableHighlight
                                style={styles.loginBtn}
                                onPress={this._submit.bind(this)}
                            >
                                <Text style={styles.loginText}>确定发布</Text>
                            </TouchableHighlight>
                        </View>
                    </View>
                </ScrollView>
                <TouchableOpacity style={styles.telphone} onPress={()=>{
                    Communications.phoneCall(this.state.telphone,false)
                }}>
                    <Text style={styles.telnumber}>联</Text>
                    <Text style={styles.telnumber}>系</Text>
                    <Text style={styles.telnumber}>电</Text>
                    <Text style={styles.telnumber}>话</Text>
                </TouchableOpacity>
            </View>
        )
    }

}

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#FFF',
        flex: 1,
        flexDirection:'column'
    },
    sliderImage:{
        width:Dimensions.get('window').width,
        height:100,
    },
    content:{
        flexDirection:'column',
    },
    head:{
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'center'
    },
    title:{
        flex:1,
        fontSize:18,
        color:'#333',
        fontWeight:'600'
    },
    scanCount:{
        fontSize:12,
        color:'#999',
    },
    service:{
        marginTop:10,
        marginBottom:10
    },
    serviceDetail:{
        color:'#898989'
    },
    tabIcon:{
        flexDirection:'row',
    },
    tabClick:{
        flexDirection:'row',
        justifyContent:"center",
        alignItems:'center',
        marginLeft:5
    },
    tabImg:{
        width:18,
        height:18
    },
    tabText:{
        marginLeft:3,
        fontSize:12
    },
    remark:{
        backgroundColor:'#eeeeeF',
        padding:10,
        flexDirection:'row',
        marginTop:10
    },
    remarkLebel:{
        marginTop:2
    },
    remarkContent:{
        flex:1,
        alignItems:'flex-start'
    },
    remarkText:{
        color:'#666'
    },
    remarkLabel:{
      marginTop:2
    },
    remarkLebelText:{
        fontWeight:'600'
    },
    remarkContentText:{
        lineHeight:20
    },
    evaInfo:{
        flexDirection:'row',
        height:34,
        borderColor:'#CCC',
        borderTopWidth:1/PixelRatio.get(),
        borderBottomWidth:1/PixelRatio.get(),
        alignItems:'center',
        marginTop:20,
        paddingLeft:5,
        paddingRight:5
    },
    infoText:{
        padding:20,
        color:'#666'
    },
    infoImg:{
        width:Dimensions.get('window').width,
    },

    nickLabel:{

    },
    nickName:{
        flex:1,
        textAlign:'center'
    },
    evaView:{
        height:120,
        borderColor:'#CCC',
        borderBottomWidth:1/PixelRatio.get(),
        paddingLeft:5
    },
    evaInput:{
        flex:1,
        alignItems:'flex-end'
    },
    loginBtn:{
        padding:15,
        backgroundColor:'#FBDC3A',
        marginTop:20,
        borderRadius:3,
        justifyContent:'center',
        alignItems:'center'
    },
    loginText:{
        fontSize:16
    },
    commentView:{
        flexDirection:'row',
        alignItems:'center',
        marginTop:5
    },
    conmentContent:{
        fontSize:14
    },
    logoImg:{
        width:30,
        height:30,
        marginRight:10,
        marginLeft:10
    },
    commentDate:{
        paddingRight:5,
    },
    commentName:{
        color:'#8FCC67'
    },
    telphone:{
        position:'absolute',
        backgroundColor:'#F00',
        right:10,
        bottom:50,
        padding:5
    },
    telnumber:{
        color:'#FFF',
        marginTop:3
    }
});

export default ServiceShop;